<template>
  <view class="flex-col">

    <view :class="boole?'bottom115':''">
      <!--基础信息-->
      <basic-info :workId="detailForm.idList"
                  :totalPrice="detailForm.totalPrice"
                  :carNum="detailForm.dtoList.length"/>

      <!--购置税信息-->
      <view class="item-wrap" style="margin-bottom: 0">
        <view class="lineBottom10">
          <uni-section title="购置税信息" type="line"/>
        </view>

        <view style="margin: 8rpx 20rpx 0 20rpx">

          <uni-forms ref="detailForm" :rules="rules" :model="detailForm"
                     :label-position="boole ? 'top' : 'left'" labelWidth="auto">
            <view style="margin-bottom: 20rpx">
              <uni-table ref="table" border stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th width="130" align="center">车架号</uni-th>
                  <uni-th width="80" align="center">发票</uni-th>
                  <uni-th width="80" align="center">合格证</uni-th>
                  <uni-th width="120" align="center">
                    <text style="color: red">*</text>
                    采购价
                  </uni-th>
                  <uni-th width="150" align="center">
                    <text style="color: red">*</text>
                    购置税费用
                  </uni-th>
                </uni-tr>
                <uni-tr v-for="(item, index) in detailForm.dtoList" :key="index">

                  <uni-td align="center">
                    <text>{{ item.vinNo }}</text>
                  </uni-td>

                  <uni-td align="center">
                    <text class="text-color" v-if="item.invoiceOss" @click="handleImg(item.invoiceOss)"> 查看</text>
                  </uni-td>

                  <uni-td align="center">
                    <text class="text-color" v-if="item.qualifiedCardOss" @click="handleImg(item.qualifiedCardOss)">
                      查看
                    </text>
                  </uni-td>

                  <uni-td align="center">
                    <uni-forms-item :name="'dtoList.'+indexB+'.purchasePrice'"
                                    v-if="!item.purchasePrice"
                                    :rules="[{ required:!item.purchasePrice, errorMessage: '请输入采购价', validateTrigger: 'blur'}]">
                      <uni-easyinput v-model="item.purchasePrice"
                                     @blur="blurTable(item,'purchasePrice')"/>
                    </uni-forms-item>
                    <text v-else>{{ item.purchasePrice }}</text>
                  </uni-td>

                  <uni-td align="center">
                    <uni-forms-item :name="'dtoList.'+indexB+'.purchaseTaxPrice'"
                                    v-if="boole"
                                    :rules="[{ required:!item.purchaseTaxPrice, errorMessage: '请输入购置税费用', validateTrigger: 'blur'}]">
                      <uni-easyinput v-model="item.purchaseTaxPrice"
                                     @blur="blurTable(item,'purchaseTaxPrice')"/>
                    </uni-forms-item>
                    <text v-else>{{ item.purchaseTaxPrice }}</text>
                  </uni-td>
                </uni-tr>
              </uni-table>
            </view>


            <uni-forms-item label="预计开始时间:" name="expectStartTime" :required="boole">
              <text class="expectStartTime"/>
              <uni-datetime-picker v-if="boole" type="date" placeholder="请选择预计开始时间"
                                   return-type="string" v-model="detailForm.expectStartTime"/>
              <text v-else>{{ detailForm.expectStartTime }}</text>
            </uni-forms-item>

            <uni-forms-item label="预计结束时间:" name="expectEndTime" :required="boole">
              <text class="expectEndTime"/>
              <uni-datetime-picker v-if="boole" type="date" placeholder="请选择预计结束时间"
                                   :start="handleDate(detailForm.expectStartTime)"
                                   return-type="string" v-model="detailForm.expectEndTime"/>
              <text v-else>{{ detailForm.expectEndTime }}</text>
            </uni-forms-item>

          </uni-forms>
        </view>
      </view>

      <!--审批流程-->
      <exam-flow v-if="flowId" :instanceId="flowId"/>

      <view class="button-container" v-if="boole">
        <button class="btn-item" @click="submit">提 交</button>
      </view>

    </view>

  </view>
</template>

<script>
import {prchaseTaxDetail, getTaxDetails, addPrchaseTax} from "@/api/purchaseTax";
import basicInfo from './components/basicInfo.vue'
import {listByIds} from '@/api/system/oss';
import {image} from "@/uni_modules/uv-ui-tools/libs/function/test";

export default {
  name: 'add',
  components: {basicInfo},
  computed: {},
  watch: {},
  data() {
    return {
      boole: false,
      flowId: null,
      detailForm: {
        idList: '',
        dtoList: []
      },
      rules: {
        expectStartTime: {
          rules: [
            {required: true, errorMessage: "请选择预计开始时间", validateTrigger: 'bind'},
          ],
        },
        expectEndTime: {
          rules: [
            {required: true, errorMessage: "请选择预计结束时间", validateTrigger: 'bind'},
          ],
        },
      },
    };
  },
  onLoad(op) {
    let title = "";
    this.flowId = op?.flowId;
    if (op?.type === "edit") {
      this.detailForm.idList = op?.id.split(',')
      this.detailForm.workOrderStatus = '2'
      this.handleEditDetail(this.detailForm.idList)
      title = "新增购置税工单";
      this.boole = true;
      console.log(op)
      if (op.businessDataId && op.businessDataId !== 'null') {
        this.handleGetTaxDetails(op?.businessDataId, op?.id)
      }
    }
    if (op?.type === "view") {
      this.detailForm.idList = op?.id.split(',')
      this.detailForm.workOrderStatus = '2'
      this.handleGetTaxDetails(op?.businessDataId, op?.id)
      title = "购置税工单详情";
      this.boole = false;
    }

    uni.setNavigationBarTitle({
      title,
    });
  },
  methods: {
    //查看图片
    async handleImg(ossId) {
      try {
        const res = await listByIds(ossId);
        const imageUrl = res.data[0]?.url;
        if (imageUrl) {
          uni.previewImage({
            urls: [imageUrl],
            fail: (err) => {
              console.error('错误:', err);
            },
          });
        } else {
          this.$modal.msgError('暂无图片')
        }
      } catch (error) {
        console.error('错误:', error);
      }
    },


    handleDate(val) {
      let date = new Date(val)
      return date.setDate(date.getDate() + 1);
    },

    //获取购置税工单
    handleEditDetail(arr) {
      prchaseTaxDetail(arr).then((res) => {
        this.detailForm.carNum = res.length
        this.detailForm.dtoList = res
        this.handeCount(this.detailForm.dtoList)
      })
    },

    handeCount(list) {
      let num = 0
      for (let i = 0; i < list.length; i++) {
        num += Math.round(Number(list[i].purchaseTaxPrice) * 100)
      }
      this.$set(this.detailForm, 'totalPrice', (num / 100).toFixed(2))
    },

    //  详情回显
    handleGetTaxDetails(val, id) {
      getTaxDetails(val).then(res => {
        if (res.code === 200) {
          for (let key in res.data) {
            this.$set(this.detailForm, key, res.data[key])
          }
          this.detailForm.workId = id
          this.detailForm.workOrderStatus = '2'
          this.handeCount(this.detailForm.dtoList)
        }
      })
    },

    blurTable(row, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!row[field]) return
      if (msg.test(Number(row[field]))) {
        if (Number(row[field]) >= 0) {
          let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
          row[field] = _value;
        } else {
          row[field] = "";
        }
      } else {
        row[field] = "";
      }
      this.handeCount(this.detailForm.dtoList)
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate().then(res => {
          resolve();
        }).catch(err => {
          let key = err[0].key;
          reject(key);
        })
      });
    },

    async submit() {
      try {
        await this.handleEffect()
        uni.showLoading();
        let res = await addPrchaseTax(this.detailForm)
        if (res.code === 200) {
          uni.$emit("refBackList", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000);
        }
      } catch (error) {
        if (typeof error === 'string') {
          this.$nextTick(() => {
            uni.pageScrollTo({
              selector: error,
            });
          });
        } else {
          console.error(error)
        }
      } finally {
        setTimeout(() => {
          uni.hideLoading();
        }, 1000);
      }
    }
  },
};
</script>

<style scoped lang="scss">
.text-color {
  color: rgb(0, 0, 255);
}
</style>


